package com.yuanqi.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqi.dto.SalesOrderAttachmentDTO;
import com.yuanqi.pojo.SalesOrderAttachment;
import com.yuanqi.service.SalesOrderAttachmentService;
import com.yuanqi.service.AttachmentTypeConfigService;
import com.yuanqi.pojo.AttachmentTypeConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售订单附件管理控制器
 */
@RestController
@RequestMapping("/api/sales/attachment")
public class SalesOrderAttachmentController {

    @Autowired
    private SalesOrderAttachmentService attachmentService;
    
    @Autowired
    private AttachmentTypeConfigService typeConfigService;

    /**
     * 上传单个附件
     * 方法名称：uploadAttachment
     * 前端调用：POST /api/sales/attachment/upload
     */
    @PostMapping("/upload")
    public Map<String, Object> uploadAttachment(
            @RequestParam("soId") Long soId,
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "description", required = false) String description,
            @RequestParam(value = "uploader", defaultValue = "admin") String uploader) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            SalesOrderAttachmentDTO result = attachmentService.uploadAttachment(soId, file, description, uploader);
            response.put("success", true);
            response.put("data", result);
            response.put("message", "附件上传成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "附件上传失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 批量上传附件
     * 方法名称：uploadAttachments
     * 前端调用：POST /api/sales/attachment/upload/batch
     */
    @PostMapping("/upload/batch")
    public Map<String, Object> uploadAttachments(
            @RequestParam("soId") Long soId,
            @RequestParam("files") MultipartFile[] files,  // 改为数组接收
            @RequestParam(value = "description", required = false) String description,
            @RequestParam(value = "uploader", defaultValue = "admin") String uploader) {
        
        Map<String, Object> response = new HashMap<>();
        
        // 添加详细的调试日志
        System.out.println("=== 批量上传附件开始 ===");
        System.out.println("订单ID: " + soId);
        System.out.println("文件数量: " + (files != null ? files.length : "null"));
        System.out.println("描述: " + description);
        System.out.println("上传人: " + uploader);
        
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                System.out.println("文件 " + (i + 1) + ": " + 
                    (file != null ? file.getOriginalFilename() + " (" + file.getSize() + " bytes)" : "null"));
            }
        }
        
        try {
            List<SalesOrderAttachmentDTO> results = attachmentService.uploadAttachments(soId, files, description, uploader);
            System.out.println("上传成功，结果数量: " + results.size());
            response.put("success", true);
            response.put("data", results);
            response.put("message", "批量附件上传成功，共上传 " + results.size() + " 个文件");
        } catch (Exception e) {
            System.out.println("上传失败，异常: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "批量附件上传失败：" + e.getMessage());
        }
        
        System.out.println("=== 批量上传附件结束 ===");
        return response;
    }

    /**
     * 下载单个附件
     * 方法名称：downloadAttachment
     * 前端调用：GET /api/sales/attachment/download/{attachmentId}
     */
    @GetMapping("/download/{attachmentId}")
    public void downloadAttachment(@PathVariable Long attachmentId, HttpServletResponse response) {
        try {
            attachmentService.downloadAttachment(attachmentId, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量下载附件（ZIP格式）
     * 方法名称：downloadAttachmentsAsZip
     * 前端调用：POST /api/sales/attachment/download/batch
     */
    @PostMapping("/download/batch")
    public void downloadAttachmentsAsZip(@RequestBody List<Long> attachmentIds, HttpServletResponse response) {
        try {
            attachmentService.downloadAttachmentsAsZip(attachmentIds, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除单个附件
     * 方法名称：deleteAttachment
     * 前端调用：DELETE /api/sales/attachment/{attachmentId}
     */
    @DeleteMapping("/{attachmentId}")
    public Map<String, Object> deleteAttachment(@PathVariable Long attachmentId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean result = attachmentService.deleteAttachment(attachmentId);
            response.put("success", result);
            response.put("message", result ? "附件删除成功" : "附件删除失败");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "附件删除失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 批量删除附件
     * 方法名称：deleteAttachments
     * 前端调用：DELETE /api/sales/attachment/batch
     */
    @DeleteMapping("/batch")
    public Map<String, Object> deleteAttachments(@RequestBody List<Long> attachmentIds) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean result = attachmentService.deleteAttachments(attachmentIds);
            response.put("success", result);
            response.put("message", result ? "批量附件删除成功" : "批量附件删除失败");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量附件删除失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 根据订单ID查询附件列表
     * 方法名称：getAttachmentsBySoId
     * 前端调用：GET /api/sales/attachment/order/{soId}
     */
    @GetMapping("/order/{soId}")
    public Map<String, Object> getAttachmentsBySoId(@PathVariable Long soId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<SalesOrderAttachmentDTO> attachments = attachmentService.getAttachmentsBySoId(soId);
            response.put("success", true);
            response.put("data", attachments);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 根据订单ID查询有效附件列表
     * 方法名称：getValidAttachmentsBySoId
     * 前端调用：GET /api/sales/attachment/order/{soId}/valid
     */
    @GetMapping("/order/{soId}/valid")
    public Map<String, Object> getValidAttachmentsBySoId(@PathVariable Long soId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<SalesOrderAttachmentDTO> attachments = attachmentService.getValidAttachmentsBySoId(soId);
            response.put("success", true);
            response.put("data", attachments);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 分页查询附件
     * 方法名称：pageAttachments
     * 前端调用：GET /api/sales/attachment/page
     */
    @GetMapping("/page")
    public Map<String, Object> pageAttachments(
            @RequestParam(defaultValue = "1") Long pageNo,
            @RequestParam(defaultValue = "10") Long pageSize,
            @RequestParam(required = false) Long soId,
            @RequestParam(required = false) String attachmentType,
            @RequestParam(required = false) String uploader) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            Page<SalesOrderAttachment> page = new Page<>(pageNo, pageSize);
            IPage<SalesOrderAttachmentDTO> result = attachmentService.pageAttachments(page, soId, attachmentType, uploader);
            
            response.put("success", true);
            response.put("data", result);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 根据附件类型查询附件列表
     * 方法名称：getAttachmentsByType
     * 前端调用：GET /api/sales/attachment/type/{attachmentType}
     */
    @GetMapping("/type/{attachmentType}")
    public Map<String, Object> getAttachmentsByType(@PathVariable String attachmentType) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<SalesOrderAttachmentDTO> attachments = attachmentService.getAttachmentsByType(attachmentType);
            response.put("success", true);
            response.put("data", attachments);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 根据上传人查询附件列表
     * 方法名称：getAttachmentsByUploader
     * 前端调用：GET /api/sales/attachment/uploader/{uploader}
     */
    @GetMapping("/uploader/{uploader}")
    public Map<String, Object> getAttachmentsByUploader(@PathVariable String uploader) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<SalesOrderAttachmentDTO> attachments = attachmentService.getAttachmentsByUploader(uploader);
            response.put("success", true);
            response.put("data", attachments);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 统计订单附件数量
     * 方法名称：countAttachmentsBySoId
     * 前端调用：GET /api/sales/attachment/count/{soId}
     */
    @GetMapping("/count/{soId}")
    public Map<String, Object> countAttachmentsBySoId(@PathVariable Long soId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long count = attachmentService.countAttachmentsBySoId(soId);
            response.put("success", true);
            response.put("data", count);
            response.put("message", "统计成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "统计失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 统计订单有效附件数量
     * 方法名称：countValidAttachmentsBySoId
     * 前端调用：GET /api/sales/attachment/count/{soId}/valid
     */
    @GetMapping("/count/{soId}/valid")
    public Map<String, Object> countValidAttachmentsBySoId(@PathVariable Long soId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long count = attachmentService.countValidAttachmentsBySoId(soId);
            response.put("success", true);
            response.put("data", count);
            response.put("message", "统计成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "统计失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 预览附件（图片类型）
     * 方法名称：previewAttachment
     * 前端调用：GET /api/sales/attachment/preview/{attachmentId}
     */
    @GetMapping("/preview/{attachmentId}")
    public ResponseEntity<byte[]> previewAttachment(@PathVariable Long attachmentId) {
        try {
            byte[] fileContent = attachmentService.previewAttachment(attachmentId);
            SalesOrderAttachmentDTO attachment = attachmentService.getAttachmentInfo(attachmentId);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", attachment.getAttachmentName());
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileContent);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取附件信息
     * 方法名称：getAttachmentInfo
     * 前端调用：GET /api/sales/attachment/info/{attachmentId}
     */
    @GetMapping("/info/{attachmentId}")
    public Map<String, Object> getAttachmentInfo(@PathVariable Long attachmentId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            SalesOrderAttachmentDTO attachment = attachmentService.getAttachmentInfo(attachmentId);
            if (attachment != null) {
                response.put("success", true);
                response.put("data", attachment);
                response.put("message", "查询成功");
            } else {
                response.put("success", false);
                response.put("message", "附件不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 更新附件描述
     * 方法名称：updateAttachmentDescription
     * 前端调用：PUT /api/sales/attachment/{attachmentId}/description
     */
    @PutMapping("/{attachmentId}/description")
    public Map<String, Object> updateAttachmentDescription(
            @PathVariable Long attachmentId,
            @RequestParam String description) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean result = attachmentService.updateAttachmentDescription(attachmentId, description);
            response.put("success", result);
            response.put("message", result ? "描述更新成功" : "描述更新失败");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "描述更新失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 检查附件是否存在
     * 方法名称：checkAttachmentExists
     * 前端调用：GET /api/sales/attachment/exists/{attachmentId}
     */
    @GetMapping("/exists/{attachmentId}")
    public Map<String, Object> checkAttachmentExists(@PathVariable Long attachmentId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean exists = attachmentService.checkAttachmentExists(attachmentId);
            response.put("success", true);
            response.put("data", exists);
            response.put("message", "检查成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 获取允许的文件类型列表
     * 方法名称：getAllowedFileTypes
     * 前端调用：GET /api/sales/attachment/allowed-types
     */
    @GetMapping("/allowed-types")
    public Map<String, Object> getAllowedFileTypes() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<String> allowedTypes = attachmentService.getAllowedFileTypes();
            response.put("success", true);
            response.put("data", allowedTypes);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 获取最大文件大小
     * 方法名称：getMaxFileSize
     * 前端调用：GET /api/sales/attachment/max-size
     */
    @GetMapping("/max-size")
    public Map<String, Object> getMaxFileSize() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            long maxSize = attachmentService.getMaxFileSize();
            response.put("success", true);
            response.put("data", maxSize);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 获取附件类型配置列表
     * 方法名称：getAttachmentTypeConfigs
     * 前端调用：GET /api/sales/attachment/type-configs
     */
    @GetMapping("/type-configs")
    public Map<String, Object> getAttachmentTypeConfigs() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<AttachmentTypeConfig> configs = typeConfigService.getEnabledOrderBySort();
            response.put("success", true);
            response.put("data", configs);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 根据类型编码获取附件类型配置
     * 方法名称：getAttachmentTypeConfigByCode
     * 前端调用：GET /api/sales/attachment/type-config/{typeCode}
     */
    @GetMapping("/type-config/{typeCode}")
    public Map<String, Object> getAttachmentTypeConfigByCode(@PathVariable String typeCode) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            AttachmentTypeConfig config = typeConfigService.getByTypeCode(typeCode);
            if (config != null) {
                response.put("success", true);
                response.put("data", config);
                response.put("message", "查询成功");
            } else {
                response.put("success", false);
                response.put("message", "配置不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }
}
